//
//  XMConfirmOrderView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/6/16.
//

#import "XMConfirmOrderView.h"
#import "XMConfirmOrderMeetCell.h"

@interface XMConfirmOrderView ()<UITableViewDelegate, UITableViewDataSource>

//@property (nonatomic, strong) UIImageView *avatarImgView;
//@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *payPriceLabel;
@property (nonatomic, strong) UILabel *discountPriceLabel;
//@property (nonatomic, strong) UILabel *totalPriceLabel;
@property (nonatomic, strong) UITextField *remarkTextField;
@property (nonatomic, strong) UIButton *selectBtn;

@property (nonatomic, strong) UITableView *tbl;

@property (nonatomic, strong) UILabel *payTotalPriceLabel;

@property (nonatomic, strong) NSDictionary *selectRowDic;
@property (nonatomic, strong) NSArray *meetBoxModelArr;
@property (nonatomic, strong) NSArray *meetModelArr;

@property (nonatomic, assign) NSInteger fromeType;  // 1.见面箱进入 2.直接下单进入

@end

@implementation XMConfirmOrderView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navTitleLabel.text = @"确认订单";
    self.backgroundColor = kColorHEX(0xF6F6F6);
    
    [self addSubview:self.tbl];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(200.0))];
    footView.backgroundColor = kColorHEX(0xF0F0F0);
    
    UIView *baseInfoBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(120.0))];
    baseInfoBgView.backgroundColor = kColorHEX(0xffffff);
    [footView addSubview:baseInfoBgView];
    
//    [baseInfoBgView addSubview:self.avatarImgView];
//    [baseInfoBgView addSubview:self.nameLabel];
//    [baseInfoBgView addSubview:self.coverImgView];
//    [baseInfoBgView addSubview:self.titleLabel];
//    [baseInfoBgView addSubview:self.dateLabel];
//    [baseInfoBgView addSubview:self.addressLabel];
    [baseInfoBgView addSubview:self.payPriceLabel];
    [baseInfoBgView addSubview:self.discountPriceLabel];
    [baseInfoBgView addSubview:self.priceLabel];
    UILabel *priceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), _priceLabel.y, self.width/2 - KScaleWidth(16.0), _priceLabel.height) font:KFontSize(15.0) textColor:kColorHEX(0x666666)];
    priceTitleLabel.text = @"产品总价";
    [baseInfoBgView addSubview:priceTitleLabel];
    
    UILabel *discountTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(priceTitleLabel.x, priceTitleLabel.maxY, priceTitleLabel.width, priceTitleLabel.height) font:KFontSize(15.0) textColor:kColorHEX(0x666666)];
    discountTitleLabel.text = @"优惠";;
    [baseInfoBgView addSubview:discountTitleLabel];
    baseInfoBgView.height = _payPriceLabel.maxY + KScaleWidth(14.0);
    
    UIView *payInfoBgView = [[UIView alloc] initWithFrame:CGRectMake(0, baseInfoBgView.maxY + KScaleWidth(8.0), self.width, KScaleWidth(225.0))];
    payInfoBgView.backgroundColor = kColorHEX(0xffffff);
    [footView addSubview:payInfoBgView];
    {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), KScaleWidth(10.0), self.width/2 - KScaleWidth(16.0), KScaleWidth(33.0)) font:KFontSize(15.0) textColor:kColorHEX(0x666666)];
        titleLabel.text = @"支付方式";
        [payInfoBgView addSubview:titleLabel];
        
        UIImageView *payIcon = [[UIImageView alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), titleLabel.maxY + KScaleWidth(10.0), KScaleWidth(30.0), KScaleWidth(30.0))];
        payIcon.image = ImageNamed(@"mine_wei_withdraw_icon");
        [payInfoBgView addSubview:payIcon];
        
        UILabel *payTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(payIcon.maxX + KScaleWidth(10.0), payIcon.y, self.width - payIcon.maxX - KScaleWidth(10.0), payIcon.height) font:KFontSize(16.0) textColor:kColorHEX(0x333333)];
        payTitleLabel.text = @"微信支付";
        [payInfoBgView addSubview:payTitleLabel];
        
        UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(self.width - KScaleWidth(10.0) - KScaleWidth(30.0), payIcon.y, KScaleWidth(30.0), payIcon.height) image:@"mine_select_icon" selectImg:@"mine_select_icon_select"];
        [selectBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
        selectBtn.selected = YES;
        [payInfoBgView addSubview:selectBtn];
        
        UILabel *explainTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), payTitleLabel.maxY + KScaleWidth(25.0), payInfoBgView.width - KScaleWidth(16.0), KScaleWidth(21.0)) font:KFontSize(15.0) textColor:kColorHEX(0x666666)];
        explainTitleLabel.text = @"安全须知";
        [payInfoBgView addSubview:explainTitleLabel];
        
        UILabel *explainLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), explainTitleLabel.maxY, self.width - KScaleWidth(16.0)*2, KScaleWidth(72.0)) font:KFontSize(13.0) textColor:kColorHEX(0x999999)];
        explainLabel.numberOfLines = 0;
        explainLabel.text = @"1.勿随身携带大量现金或贵重物品，建议使用电子支付。\n2.安全永远是第一优先级，平台仅是工具，自我保护意识才是核心防线。\n3.下单即代表你同意《用户服务协议》";
        [payInfoBgView addSubview:explainLabel];
    }
    
    UIView *remarkBgView = [[UIView alloc] initWithFrame:CGRectMake(0, payInfoBgView.maxY + KScaleWidth(8.0), self.width, KScaleWidth(38.0))];
    remarkBgView.backgroundColor = kColorHEX(0xffffff);
    [footView addSubview:remarkBgView];
    
    UILabel *remarkTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), 0, remarkBgView.width/2 - KScaleWidth(16.0), remarkBgView.height) font:KFontSize(15.0) textColor:kColorHEX(0x666666)];
    remarkTitleLabel.text = @"订单备注";
    [remarkBgView addSubview:remarkTitleLabel];
    [remarkBgView addSubview:self.remarkTextField];
    
    footView.height = remarkBgView.maxY;
    _tbl.tableFooterView = footView;
    
    [self addSubview:self.payTotalPriceLabel];
    UIButton *payBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KBoldFontSize(14.0) frame:CGRectMake(self.width - KScaleWidth(16.0) - KScaleWidth(100.0), self.height - kTabBarH + (kTabBarH - kBottomLayout - KScaleWidth(38.0))/2, KScaleWidth(100.0), KScaleWidth(38.0)) title:@"立即付款" titleColor:kColorHEX(0x333333)];
    [payBtn setGradientLayerWithLocations:@[@(0), @(1.0)] colors:@[(__bridge id)kColorHEX(0xFFD800).CGColor, (__bridge id)kColorHEX(0xFFE44E).CGColor] startPoint:CGPointMake(0.5, 0.37) endPoint:CGPointMake(0.5, 0.03)];
    [payBtn setCornerRadius:payBtn.height/2];
    [payBtn addTarget:self action:@selector(payAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:payBtn];
}

//购物车来的
- (void)setContentWithMeetModelArr:(NSArray *)meetBoxModelArr
                      selectRowDic:(nonnull NSDictionary *)selectRowDic {
    _meetBoxModelArr = meetBoxModelArr;
    _selectRowDic = selectRowDic;
    _fromeType = 1;
    [_tbl reloadData];
    CGFloat price = 0;
    if (selectRowDic.count > 0) {
        NSArray *keys = [selectRowDic allKeys];
        for (int i = 0; i < keys.count; i ++) {
            NSString *keyStr = keys[i];
            NSArray *selectRows = [selectRowDic safeArrayForKey:keyStr];
            for (NSString *rowStr in selectRows) {
                XMMeetBoxModel *boxModel = meetBoxModelArr[[keyStr integerValue]];
                XMServiceVosModel *serviceModel = boxModel.serviceVos[[rowStr integerValue]];
                price += [serviceModel.price floatValue];
            }
        }
    }
    _priceLabel.text = [NSString stringWithFormat:@"¥%.2f", price];
//    _payPriceLabel.text = [NSString stringWithFormat:@"¥%.2f", price];
    NSString *payPriceStr = [NSString stringWithFormat:@"需付款 ¥%.2f", price];
    NSMutableAttributedString *payPriceAttr = [[NSMutableAttributedString alloc] initWithString:payPriceStr attributes:@{NSFontAttributeName : KBoldFontSize(18.0), NSForegroundColorAttributeName : kColorHEX(0xDD4B39)}];
    [payPriceAttr addAttributes:@{NSFontAttributeName : KFontSize(16.0), NSForegroundColorAttributeName : kColorHEX(0x333333)} range:NSMakeRange(0, 3)];
    [_payPriceLabel setAttributedText:payPriceAttr];
    _discountPriceLabel.text = @"暂无优惠";
    
    NSString *payTotalPriceStr = [NSString stringWithFormat:@"总计：¥%.2f", price];
    NSMutableAttributedString *payTotalPriceAttr = [[NSMutableAttributedString alloc] initWithString:payTotalPriceStr attributes:@{NSFontAttributeName : KBoldFontSize(20.0), NSForegroundColorAttributeName : kColorHEX(0x333333)}];
    [payTotalPriceAttr addAttributes:@{NSFontAttributeName : KFontSize(16.0)} range:NSMakeRange(0, 3)];
    [_payTotalPriceLabel setAttributedText:payTotalPriceAttr];
//    [_avatarImgView sd_setImageWithURL:[NSURL URLWithString:meetDetailModel.authorVo.avatar] placeholderImage:ImageNamed(@"mine_avatar_icon")];
//    _nameLabel.text = meetDetailModel.authorVo.nickname;
//    [_coverImgView sd_setImageWithURL:[NSURL URLWithString:meetDetailModel.coverImageUrl]];
//    _titleLabel.text = meetDetailModel.title;
//    _dateLabel.text = meetDetailModel.startTimeStr;
//    _addressLabel.text = [NSString stringWithFormat:@"%@%@%@", meetDetailModel.addrProvince, meetDetailModel.addrCity, meetDetailModel.addrDetail];
//    _priceLabel.text = [NSString stringWithFormat:@"¥%@", meetDetailModel.totalPrice];
//    _payPriceLabel.text = [NSString stringWithFormat:@"¥%@", meetDetailModel.totalPrice];
//    NSString *payPriceStr = [NSString stringWithFormat:@"需付款 ¥%@", meetDetailModel.totalPrice];
//    NSMutableAttributedString *payPriceAttr = [[NSMutableAttributedString alloc] initWithString:payPriceStr attributes:@{NSFontAttributeName : KBoldFontSize(18.0), NSForegroundColorAttributeName : kColorHEX(0xDD4B39)}];
//    [payPriceAttr addAttributes:@{NSFontAttributeName : KFontSize(16.0), NSForegroundColorAttributeName : kColorHEX(0x333333)} range:NSMakeRange(0, 3)];
//    [_payPriceLabel setAttributedText:payPriceAttr];
//
//    NSString *payTotalPriceStr = [NSString stringWithFormat:@"总计：¥%@", meetDetailModel.totalPrice];
//    NSMutableAttributedString *payTotalPriceAttr = [[NSMutableAttributedString alloc] initWithString:payTotalPriceStr attributes:@{NSFontAttributeName : KBoldFontSize(20.0), NSForegroundColorAttributeName : kColorHEX(0x333333)}];
//    [payTotalPriceAttr addAttributes:@{NSFontAttributeName : KFontSize(16.0)} range:NSMakeRange(0, 3)];
//    [_payTotalPriceLabel setAttributedText:payTotalPriceAttr];
}

//直接下单
- (void)setContentWithModelArr:(NSArray *)modelArr {
    _meetModelArr = modelArr;
    _fromeType = 2;
    [_tbl reloadData];
    XMMeetDetailModel *detailModel = [modelArr firstObject];
    _priceLabel.text = [NSString stringWithFormat:@"¥%@", detailModel.totalPrice];
//    _payPriceLabel.text = [NSString stringWithFormat:@"¥%.2f", price];
    NSString *payPriceStr = [NSString stringWithFormat:@"需付款 ¥%@", detailModel.totalPrice];
    NSMutableAttributedString *payPriceAttr = [[NSMutableAttributedString alloc] initWithString:payPriceStr attributes:@{NSFontAttributeName : KBoldFontSize(18.0), NSForegroundColorAttributeName : kColorHEX(0xDD4B39)}];
    [payPriceAttr addAttributes:@{NSFontAttributeName : KFontSize(16.0), NSForegroundColorAttributeName : kColorHEX(0x333333)} range:NSMakeRange(0, 3)];
    [_payPriceLabel setAttributedText:payPriceAttr];
    
    NSString *payTotalPriceStr = [NSString stringWithFormat:@"总计：¥%@", detailModel.totalPrice];
    NSMutableAttributedString *payTotalPriceAttr = [[NSMutableAttributedString alloc] initWithString:payTotalPriceStr attributes:@{NSFontAttributeName : KBoldFontSize(20.0), NSForegroundColorAttributeName : kColorHEX(0x333333)}];
    [payTotalPriceAttr addAttributes:@{NSFontAttributeName : KFontSize(16.0)} range:NSMakeRange(0, 3)];
    [_payTotalPriceLabel setAttributedText:payTotalPriceAttr];
}

//立即支付
- (void)payAction:(UIButton *)button {
    if (self.meetBoxModelArr && self.meetBoxModelArr.count > 0) {
        NSString *cartIds = @"";
        NSArray *keys = [self.selectRowDic allKeys];
        for (int i = 0; i < keys.count; i ++) {
            NSString *keyStr = keys[i];
            NSArray *rowArr = [self.selectRowDic safeArrayForKey:keyStr];
            XMMeetBoxModel *boxModel = self.meetBoxModelArr[[keyStr integerValue]];
            for (NSString *rowStr in rowArr) {
                XMServiceVosModel *serviceModel = boxModel.serviceVos[[rowStr integerValue]];
                if (cartIds.length > 0) {
                    cartIds = [cartIds stringByAppendingFormat:@",%@", serviceModel.cartId];
                }
                else {
                    cartIds = serviceModel.cartId;
                }
            }
        }
        NSString *priceStr = [_priceLabel.text stringByReplacingOccurrencesOfString:@"¥" withString:@""];
        self.payBlock ? self.payBlock(cartIds, priceStr) : nil;
    }
    else {
        XMMeetDetailModel *detailModel = [_meetModelArr firstObject];
        self.payBlock ? self.payBlock(detailModel.objectId, detailModel.totalPrice) : nil;
    }
}

- (void)selectAction:(UIButton *)button {
    button.selected = YES;
}

#pragma mark - Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_fromeType == 1) {
        return [_selectRowDic allKeys].count;
    }
    else if (_fromeType == 2) {
        return _meetModelArr.count;
    }
    else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_fromeType == 1) {
//        XMMeetBoxModel *meetBoxModel = _meetBoxModelArr[[[_selectRowDic allKeys][section] integerValue]];
        NSString *keyStr = [_selectRowDic allKeys][section];
        return [_selectRowDic safeArrayForKey:keyStr].count;
    }
    else if (_fromeType == 2) {
        return 1;
    }
    else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return KScaleWidth(65.0);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(65.0))];
    headView.backgroundColor = kColorHEX(0xffffff);
    UIImageView *avatarImgView = [[UIImageView alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), (headView.height - KScaleWidth(35.0))/2, KScaleWidth(35.0), KScaleWidth(35.0))];
    [avatarImgView setCornerRadius:avatarImgView.height/2];
    [headView addSubview:avatarImgView];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(avatarImgView.maxX + KScaleWidth(8.0), 0, headView.width - avatarImgView.maxX - KScaleWidth(8.0), headView.height) font:KFontSize(18.0) textColor:kColorHEX(0x333333)];
    [headView addSubview:nameLabel];
    
    if (_fromeType == 1) {
        XMMeetBoxModel *meetBoxModel = _meetBoxModelArr[[[_selectRowDic allKeys][section] integerValue]];
        [avatarImgView sd_setImageWithURL:[NSURL URLWithString:meetBoxModel.avatar] placeholderImage:ImageNamed(@"mine_avatar_icon")];
        nameLabel.text = meetBoxModel.nickname;
    }
    else if (_fromeType == 2) {
        XMMeetDetailModel *detailModel = _meetModelArr[section];
        [avatarImgView sd_setImageWithURL:[NSURL URLWithString:detailModel.authorVo.avatar] placeholderImage:ImageNamed(@"mine_avatar_icon")];
        nameLabel.text = detailModel.authorVo.nickname;
    }
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScaleWidth(100.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMConfirmOrderMeetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMConfirmOrderMeetCellName"];
    if (_fromeType == 1) {
        NSString *keyStr = [_selectRowDic allKeys][indexPath.section];
        XMMeetBoxModel *meetBoxModel = _meetBoxModelArr[[keyStr integerValue]];
        NSString *rowStr = [_selectRowDic safeArrayForKey:keyStr][indexPath.row];
        [cell setContentWithServiceModel:meetBoxModel.serviceVos[[rowStr integerValue]]];
    }
    else if (_fromeType == 2) {
        XMMeetDetailModel *detailModel = _meetModelArr[indexPath.row];
        [cell setContentWithMeetDetailModel:detailModel];
    }
    return cell;
}

#pragma mark - Init
- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - kNavagationBarH - kTabBarH)];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        _tbl.backgroundColor = kColorHEX(0xF6F6F6);
        _tbl.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tbl registerClass:[XMConfirmOrderMeetCell class] forCellReuseIdentifier:@"XMConfirmOrderMeetCellName"];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
    }
    return _tbl;
}

//- (UIImageView *)avatarImgView {
//    if (!_avatarImgView) {
//        _avatarImgView = [[UIImageView alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), KScaleWidth(16.0), KScaleWidth(36.0), KScaleWidth(36.0))];
//        [_avatarImgView setCornerRadius:_avatarImgView.height/2];
//    }
//    return _avatarImgView;
//}
//
//- (UILabel *)nameLabel {
//    if (!_nameLabel) {
//        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(60.0), self.avatarImgView.y, self.width - KScaleWidth(60.0), _avatarImgView.height) font:KFontSize(18.0) textColor:kColorHEX(0x333333)];
//    }
//    return _nameLabel;
//}

- (UILabel *)priceLabel {
    if (!_priceLabel) {
        _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width/2, KScaleWidth(20.0), self.width/2 - KScaleWidth(16.0), KScaleWidth(40.0)) font:KBoldFontSize(18.0) textColor:kColorHEX(0x333333) textAlignment:NSTextAlignmentRight];
    }
    return _priceLabel;
}

- (UILabel *)discountPriceLabel {
    if (!_discountPriceLabel) {
        _discountPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.priceLabel.x, _priceLabel.maxY, _priceLabel.width, _priceLabel.height) font:KBoldFontSize(18.0) textColor:kColorHEX(0x333333) textAlignment:NSTextAlignmentRight];
    }
    return _discountPriceLabel;
}

- (UILabel *)payPriceLabel {
    if (!_payPriceLabel) {
        _payPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width/2, self.discountPriceLabel.maxY + KScaleWidth(20.0), self.width/2 - KScaleWidth(16.0), KScaleWidth(30.0))];
        _payPriceLabel.textAlignment = NSTextAlignmentRight;
    }
    return _payPriceLabel;
}

- (UITextField *)remarkTextField {
    if (!_remarkTextField) {
        _remarkTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.width/2, 0, self.width/2 - KScaleWidth(16.0), KScaleWidth(38.0))];
        _remarkTextField.textAlignment = NSTextAlignmentRight;
        _remarkTextField.font = KFontSize(13.0);
        _remarkTextField.placeholder = @"和发布者协商一致后留言";
    }
    return _remarkTextField;
}

- (UILabel *)payTotalPriceLabel {
    if (!_payTotalPriceLabel) {
        _payTotalPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), self.height - kTabBarH, self.width/2 - KScaleWidth(16.0), kTabBarH - kBottomLayout)];
    }
    return _payTotalPriceLabel;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
